package com.zhaokuner.rabbitmq.boot;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

@Component
public class RabbimtMQListener {

    AtomicInteger index = new AtomicInteger(1);

    @RabbitListener(queues = "boot_queue")
    public void ListenerQueue(Message message, Channel channel) {
        System.out.println(new String(message.getBody()));
        try {
            Thread.sleep(1000);
            System.out.println(index.get());
            if (index.getAndIncrement() % 5 == 0) {
                System.out.println(index + "~~~~ACK~~~~~~~");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                System.out.println(index + "----NCK--------");
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
